package com.management.department.teacherinfosystem.config;

import com.management.department.teacherinfosystem.security.JwtAuthFilter;
import com.management.department.teacherinfosystem.Service.CustomUserDetailsService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

/**
 * Spring‑Security 6.1+ 版本安全配置<br/>
 * <ul>
 *     <li>采用 JWT 无状态认证</li>
 *     <li>Lambda DSL（替代 and()）</li>
 *     <li>按路径粒度做最小拦截 —— /api/auth/** 放行；/api/user/** 管理员；其他需登录</li>
 * </ul>
 */
@Configuration
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthFilter jwtAuthFilter;
    private final CustomUserDetailsService userDetailsService;

    /** BCrypt 加密器 */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /** AuthenticationManager（Spring‑Boot 3 / Security 6 需手动暴露） */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration cfg) throws Exception {
        return cfg.getAuthenticationManager();
    }

    /** CORS 配置（允许常用方法与头部） */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration cfg = new CorsConfiguration();
        cfg.setAllowedOriginPatterns(List.of("*"));
        cfg.setAllowedMethods(List.of("GET","POST","PUT","PATCH","DELETE","OPTIONS"));
        cfg.setAllowedHeaders(List.of("*"));
        cfg.setExposedHeaders(List.of("Content-Disposition"));
        cfg.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", cfg);
        return source;
    }

    /** 核心过滤链 */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
                // 关闭 CSRF，启用 CORS（默认即可）
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 无状态
                .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 路径权限
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        .requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/auth/**").permitAll()
                        .requestMatchers("/actuator/**").permitAll()
                        .requestMatchers("/api/user/me", "/api/user/change_password").authenticated()
                        .requestMatchers(HttpMethod.GET, "/api/role/list").hasAnyRole("ADMIN", "MANAGER")
                        .requestMatchers("/api/user/**").hasRole("ADMIN")
                        .anyRequest().authenticated())
                // 异常处理（未登录 401）
                .exceptionHandling(ex -> ex.authenticationEntryPoint((req, res, e) -> {
                    // 对 actuator/health 放行（即使到达此处也返回 200）
                    String uri = req.getRequestURI();
                    if (uri != null && uri.startsWith("/actuator/health")) {
                        res.setStatus(HttpServletResponse.SC_OK);
                        return;
                    }
                    res.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
                }))
                // 指定自定义 userDetailsService
                .userDetailsService(userDetailsService)
                // JWT 过滤器在 UsernamePasswordAuthenticationFilter 之前
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
